<script setup>
import { fileSize, extname } from '@/utils/tool'

const props = defineProps({
    exts: {
        type: Array,
        default: ['.jpg', '.jpeg', '.bmp', '.webp', '.gif', '.png']
    },
    maxSize: {
        type: Number,
        default: 1024 ** 2
    }
})

const emit = defineEmits(['drop'])

const dragging = ref(false)
const validExt = (name) => props.exts.includes(extname(name));
const validSize = (size) => size <= props.maxSize;

const dragover = (e) => {
    if(!e.dataTransfer.types.includes('Files')){
        return
    }
    e.preventDefault()
    dragging.value = true
}
const dragleave = (e) => {
    e.preventDefault();
    dragging.value = false;
}
const drop = async (e) => {
    e.preventDefault();
    dragging.value = false;
    let results = await Promise.all([...e.dataTransfer.items].map((item) =>
        handleEntry(item.webkitGetAsEntry())
    ));
    results = results.flat(Infinity).filter((f) => validExt(f.name) && validSize(f.size));
    // console.log(results)
    emit('drop', results);
}

const handleEntry = (entry) => {
    return new Promise((resolve) => {
        if (entry.isFile) {
        entry.file(resolve);
        return;
        }
        const dirReader = entry.createReader();
        dirReader.readEntries(async (entries) => {
                resolve(await Promise.all(entries.map(handleEntry)));
            });
    });
}
</script>

<template>
     <div :class="['drag', {dragging: !!dragging}]" @dragover="dragover" @dragenter="dragover" @dragleave="dragleave" @drop="drop" >
        <div class="icon-box">
            <span class="iconfont icon-upload"></span>
            <div class="text">将目录或多个文件拖拽到此处进行扫描</div>
        </div>
        <div class="text-box">
            <div class="text">支持的文件类型：{{ exts.join('、') }}</div>
            <div class="text">每个文件允许大小不超过{{ fileSize(maxSize, true) }}</div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
 .drag{
    width: inherit;
    margin-top: 0;
    height: 280px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #f0f0f0;
    outline: 2px dashed #ccc;
    border-radius: 10px;
    gap: 20px;
    &.dragging{
        outline: 2px dashed #197CFD;
        background: #e6f7ff;
    }
    .icon-box{
        display: flex;
        align-items: center;
        gap: 20px;
        .icon-upload{
            font-size: 40px;
            color: #999;
        }
        .text{
            font-size: 16px;
            color: #999;
        }
    }
    .text-box{
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 20px;
        .text{
            font-size: 16px;
            color: #999;
        } 
    }
}
</style>